package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import artid.com.arttogoa.R;

import artid.com.arttogoa.adapter.InquiryAdapter;
import artid.com.arttogoa.util.SendHxMessage_Utils;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：InquiryActivity   
 * 类描述：询价列表页   
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午2:22:50      
 *
 */
public class InquiryActivity extends BaseActivity implements OnClickListener{
	private ListView mListview;
	private InquiryAdapter adapter;
	private Context mContext;
	private List<EMConversation> conversationList;
	private LinearLayout nullDataLL;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				conversationList.clear();
				conversationList.addAll(loadConversationsWithRecentChat());
				if (adapter == null && conversationList != null && conversationList.size() != 0) {
					nullDataLL.setVisibility(View.GONE);
					adapter = new InquiryAdapter(mContext,conversationList);
					mListview.setAdapter(adapter);
				}else if (adapter != null && conversationList != null && conversationList.size() != 0) {
					nullDataLL.setVisibility(View.GONE);
					adapter.notifyDataSetChanged();
				}else if(conversationList==null || conversationList.size() == 0){
					nullDataLL.setVisibility(View.VISIBLE);
					return;
				}
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inquiry);
		setContent(this, getIntent());
		mContext = this;
		initView();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		refreshHxMessage();
	}

	private void initView(){
		conversationList = new ArrayList<EMConversation>();
		EMClient.getInstance().chatManager().addMessageListener(msgListener);
		nullDataLL=(LinearLayout) findViewById(R.id.Inquiry_noData);
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("询价列表页");
		setBack();
		mListview = (ListView) findViewById(R.id.inquiry_list);
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 进入聊天页面
				SendHxMessage_Utils.goChat(mContext, conversationList.get(position).getLastMessage());
			}
		});
	}

	/**
	 * 刷新环信会话列表
	 */
	public void refreshHxMessage() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(1);
			}
		}).start();
	}

	/**
	 * 获取所有会话
	 * 
	 * @param context
	 * @return +
	 */
	private List<EMConversation> loadConversationsWithRecentChat() {
		// 获取所有会话，包括陌生人
		Map<String, EMConversation> conversations = EMClient.getInstance()
				.chatManager().getAllConversations();
		// 过滤掉messages size为0的conversation
		/**
		 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
		 * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
		 */
		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					sortList.add(new Pair<Long, EMConversation>(conversation
							.getLastMessage().getMsgTime(), conversation));
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<EMConversation> list = new ArrayList<EMConversation>();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			list.add(sortItem.second);
		}
		for (int i = 0; i < list.size(); i++) {
			Log.d("log", "环信会话列表：" + list.get(i).getLastMessage().toString());
		}

		return list;
	}

	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortConversationByLastChatTime(
			List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList,
				new Comparator<Pair<Long, EMConversation>>() {
			@Override
			public int compare(final Pair<Long, EMConversation> con1,
					final Pair<Long, EMConversation> con2) {

				if (con1.first == con2.first) {
					return 0;
				} else if (con2.first > con1.first) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}
	
	
	/**
	 * 环信消息接收
	 */
	EMMessageListener msgListener = new EMMessageListener() {

		@Override
		public void onCmdMessageReceived(List<EMMessage> list_EMMessage) {
			// TODO Auto-generated method stub
			// 透传消息
			Log.d("log", "环信透传消息:" + list_EMMessage.toString());

		}

		@Override
		public void onMessageRead(List<EMMessage> list) {
			// 已读回执
		}

		@Override
		public void onMessageDelivered(List<EMMessage> list) {
			// 已送达
		}

		@Override
		public void onMessageChanged(EMMessage arg0, Object arg1) {
			// TODO Auto-generated method stub
			// 消息状态变动
		}

		@Override
		public void onMessageReceived(List<EMMessage> list_EMMessage) {
			// TODO Auto-generated method stub
			// 收到消息
			Log.d("log", "环信消息:" + list_EMMessage.toString());
			refreshHxMessage();
		}
	};


	@Override
	public void onClick(View v) {

	}
}
